//! 已停止
const puppeteer = require("puppeteer");
const moment = require("moment");

const { createMobile, config } = require("../../../common/mobile");
const {
  info,
  saveFile,
  logging,
  timeout,
  reporter
} = require("../../../common/util");

const name = "a1";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/au/a1/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);
logger.info(info.proxy);
(async () => {
  const browser = await puppeteer.launch(config);
  // const [page] = await browser.pages();
  const page = await browser.newPage();

  const m = await createMobile(page);

  //sub status linstener
  m._page.on("response", response => {
    let url = response.url();
    let status = response.status();

    if (url.startsWith("http")) {
      logger.info(`${response.request().method()}`, status, url);
    }

    if (url.startsWith("http://at.ifunnyhub.com")) {
      r.s("success");
    }

    if (url.startsWith("http://google.com")) {
      r.w("failure", url);
      m.close();
    }
  });

  //开始
  try {
    r.i("start");

    logger.info("start");

    await m.get(`http://dat.c4fungames.com/dm/at/lp`);

    //等待页面加载完成
    await m._page.waitForSelector("input[id=agree]", { timeout });
    await m._page.waitForSelector("button[id=submit_btn_mobile]", { timeout });

    await m.sleep(1000);

    //保存页面
    saveFile(`${logdir}/1.html`, await m._page.content());

    logger.info("save page done");

    //勾选
    await m.evaluate(() => {
      document.getElementById("agree").click();
    });

    await r.i("sub_click");

    await logger.info("click");

    await m.sleep(5 * 1000);

    // 点击订阅按钮
    // await m.tapElement("button[id='submit_btn_mobile']");
    await m.evaluate(() => {
      document.getElementById("submit_btn_mobile").click();
    });

    //等待测试
    await logger.info("click2");
    await m._page.waitForSelector("input[id='vasb-agb-input']", { timeout });
    await m._page.waitForSelector("input[id='vasb-fagg-input']", { timeout });
    await m._page.waitForSelector(`button[name='confirm']`, { timeout });

    await logger.info("enter click page");

    await m.evaluate(() => {
      document.getElementById("vasb-agb-input").click();
    });
    await m.evaluate(() => {
      document.getElementById("vasb-fagg-input").click();
    });

    await m.sleep(5 * 1000);

    await logger.info("click checkbox");

    // await m.tapElement("button[name='confirm']");

    await logger.info("submit");

    saveFile(`${logdir}/2.html`, await m._page.content());

    logger.info("end");

    await r.i("end");
  } catch (e) {
    saveFile(`${logdir}/error.html`, await m._page.content());
    r.e(e + "");
    console.log(e);
  } finally {
    m.close();
  }

  await browser.close();
})();
